package com.ciban.smarthome.module.engine;

import android.content.Context;

import com.ciban.smarthome.common.utils.logcrash.LogUtil;
import com.ciban.smarthome.module.db.dao.CurtainDao;
import com.ciban.smarthome.module.engine.base.BaseEngine;
import com.ciban.smarthome.module.entity.Equip_Curtain;
import com.ciban.smarthome.module.entity.Host;
import com.ciban.smarthome.module.net.communication.Communicate;
import com.ciban.smarthome.module.net.communication.ProtocolHelper;

import java.util.ArrayList;

/**
 * Created by wdl on 2015/11/10.
 * 窗帘的管理类
 */
public class CurtainEngine extends BaseEngine {

    private CurtainDao dao;
    private ArrayList<Equip_Curtain> curtainList;
    private Host host;
    private String area_id;
    private int type; //设备类型

    public CurtainEngine(Context context) {
        super(context);
    }

    public CurtainEngine(Context context, String area_id, int type) {
        super(context);
        this.area_id = area_id;
        this.type = type;
        host = getHostInfo(area_id);
    }

    public void refreshCurtainList() {
        curtainList.clear();
        curtainList.addAll(getCurtainListFromDb(area_id, type));
    }

    private ArrayList<Equip_Curtain> getCurtainListFromDb(String area_id, int type) {
        checkDao();
        return dao.getCurtainList(area_id, type);
    }

    public ArrayList<Equip_Curtain> getCurtainList() {
        if (curtainList == null)
            curtainList = getCurtainListFromDb(area_id, type);
        LogUtil.info("获取的区域对应的窗帘的列表："+curtainList.size());
        return curtainList;
    }

    public void sendCmd(int cmdType, Equip_Curtain info, Communicate.ConnListener listener) {
        String cmd = ProtocolHelper.getNormalCmd(host,
                info.getSerial_no(), cmdType);
        sendCmd(cmd,listener);
    }

    public void sendCmd(String cmd, Communicate.ConnListener listener) {
        sendData(cmd,host,listener);
    }

    /**
     * 添加新的窗帘
     *
     * @param info
     * @return
     */
    public boolean addNewCurtain(Equip_Curtain info) {
        checkDao();
        LogUtil.info("添加的窗帘的信息："+info.toString());
        String id = addNewEquipMent(info);
        info.setId(id);
        LogUtil.info("新添加窗帘的id为："+id);
        return dao.addNewCurtain(info) > 0;
    }

    /**
     * 更新窗帘信息
     *
     * @param info
     * @return
     */
    public boolean updateCurtain(Equip_Curtain info) {
        checkDao();
        boolean b = upEquipment(info) > 0;
        return dao.upCurtain(info) > 0 | b;
    }

    /**
     * 删除投影仪
     *
     * @param info
     * @return
     */
    public boolean delCurtain(Equip_Curtain info) {
        checkDao();
        delEquipment(info);
        return dao.delCurtain(info.getId()) > 0;
    }


    private void checkDao() {
        if (dao == null)
            dao = new CurtainDao(context);
    }
}
